﻿/*
 * 创建人：申永康
 * 创建时间：2022/8/16
 * 
 * *******************************************************************
 * 
 * 功能描述：部门服务
 * 
 * *******************************************************************
 * 修改履历：
 * 申永康 20220816 创建文件
 * 申永康 20220816 添加注释
 * 
 * *******************************************************************
 */
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using XfTechOAWeb.Data;
using XfTechOAWeb.Models;
using XfTechOAWeb.Dtos.Departments;
using XfTechOAWeb.Dtos;
using System.ComponentModel.DataAnnotations;
using XfTechOAWeb.EFCore.Base;

namespace XfTechOAWeb.EFCore
{
    /// <summary>
    /// 部门模块-仓储实现类
    /// </summary>
    public class DepartmentRepository : EfBaseRepository<Department>, IDepartmentRepository
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">上下文注入</param>
        public DepartmentRepository(DbContext db) : base(db)
        {
            _db = db;
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Dels(string id)
        {
            _db.Database.ExecuteSqlRaw($"update Departments set IsChecks+=1 where DepId in ({id})");
            return _db.SaveChanges();
        }

        /// <summary>
        /// 部门停用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Upts(int id)
        {
            _db.Database.ExecuteSqlRaw($"update Departments set Status=0 where DepId in ({id})");
            return _db.SaveChanges();
        }
        /// <summary>
        /// 部门分页显示
        /// </summary>
        /// <param name="Pindex"></param>
        /// <param name="Psize"></param>
        /// <param name="did"></param>
        /// <returns></returns>

        public PageResponseModel<DepartmentDto> DShow(int Pindex = 1, int Psize = 10)
        {
            var ls = from A in _db.Set<Department>().Where(x => x.IsChecks == 0).AsQueryable()
                     select
                     new DepartmentDto
                     {
                         Account = string.Join(',', (from B in _db.Set<User>() join C in _db.Set<DepartmentsUser>() on B.UId equals C.UId where C.DepId == A.DepId select B.UName).ToArray()),
                         DUId = A.DepId,
                         Name = A.Name,
                         ParentId = A.ParentId,
                         Status = A.Status,
                         CreatedTime = A.CreatedTime,
                         IsChecks = A.IsChecks,
                         DepId = A.DepId,
                     };
            PageResponseModel<DepartmentDto> p = new PageResponseModel<DepartmentDto>()
            {
                TotalCount = ls.Count(),
                PageList = ls.OrderBy(x => x.DepId).Skip((Pindex - 1) * Psize).Take(Psize).ToList(),
            };
            return p;
        }

        /// <summary>
        /// 部门树形显示
        /// </summary>
        /// <returns></returns>
        public List<Department> Show()
        {
            var slist = _db.Set<Department>().Where(x => x.ParentId == 0).ToList();
            //调用递归方法
            ChildrenMshow(slist);
            return slist;
        }

        /// <summary>
        /// 递归子方法
        /// </summary>
        /// <param name="dd"></param>
        private void ChildrenMshow(List<Department> dd)
        {
            foreach (var item in dd)
            {
                item.Dlist = new List<Department>();
                item.Dlist = _db.Set<Department>().Where(x => x.ParentId == item.DepId).ToList();
                ChildrenMshow(item.Dlist);
            }
        }

        /// <summary>
        /// 部门添加用户
        /// </summary>
        /// <param name="depId"></param>
        /// <param name="uId"></param>
        /// <returns></returns>

        public int AddDepartmentsUser(int depId, string uId)
        {
            using (var tran = _db.Database.BeginTransaction())
            {
                try
                {
                    int affectRows = _db.Database.ExecuteSqlInterpolated($"delete from DepartmentsUser where DepId={depId}");

                    uId.Split(',').ToList().ForEach(userId =>
                    {
                        affectRows += _db.Database.ExecuteSqlInterpolated(
                                        $"insert into DepartmentsUser values(null, {depId},{userId})"
                                            );
                    });

                    tran.Commit();
                    return affectRows; //返回受影响行数
                }
                catch (Exception ex)
                {
                    //记录日志
                    tran.Rollback();
                    return -1;
                }
            }
        }

        /// <summary>
        /// 部门添加
        /// </summary>
        /// <param name="department"></param>
        /// <returns></returns>

        ResponseModel<AddDepartmentsDto> IDepartmentRepository.Add(AddDepartmentsDto department)
        {
            Department departments = new Department()
            {
                Name = department.Name,
                ParentId = department.ParentId,
                Status = department.Status,
            };
            //添加
            _db.Add(departments);
            //实例化结果返回模型
            int res = _db.SaveChanges();
            if (res > 0)
            {
                ResponseModel<AddDepartmentsDto> responseModel = new ResponseModel<AddDepartmentsDto>()
                {
                    Code = 200,
                    Msg = "添加成功!",
                    Data = department,
                };
                return responseModel;
            }
            else
            {
                ResponseModel<AddDepartmentsDto> responseModel = new ResponseModel<AddDepartmentsDto>()
                {
                    Code = 401,
                    Msg = "添加失败!",
                };
                return responseModel;
            }
        }
    }
}
